package znet

import (
	"fmt"
	"strconv"
	"zinx/ziface"
)


type MsgHandle struct{
	Apis map[uint32] ziface.IRouter //存放每个MsgId 所对应的处理方法的map属性
}

func NewMsgHandle() *MsgHandle {
	return &MsgHandle {
		Apis:make(map[uint32]ziface.IRouter),
	}
}

//调度/执行对应的Router消息处理方法
func (mh *MsgHandle) DoMsgHandler(request ziface.IRequest)	{
	//从Request中找到MsgId
	handler, ok := mh.Apis[request.GetMsgId()]
	if !ok {                                        //看看有没有对应的方法
		fmt.Println("api msgId = ", request.GetMsgId(), " is not FOUND!")
		return
	}
	//根据MsgId调度相应的业务
	handler.PreHandle(request)
	handler.Handle(request)
	handler.PostHandle(request)
}
//为消息添加具体的处理逻辑
func (mh *MsgHandle) AddRouter(msgId uint32, router ziface.IRouter) {
	//1 判断当前msg绑定的API处理方法是否已经存在
	if _, ok := mh.Apis[msgId]; ok {          //从map中取id，看是否存在
		panic("repeated api , msgId = " + strconv.Itoa(int(msgId)))      //字符串转int：Atoi()   int转字符串: Itoa()
	}
	//2 添加msg与api的绑定关系
	mh.Apis[msgId] = router                //就是一个id对应一个路由规则
	fmt.Println("Add api msgId = ", msgId)
}